package com.fzc.rhinooffice.module.workbench;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.util.JsonReader;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.fzc.rhinooffice.R;
import com.fzc.rhinooffice.common.RemoteInvoke;
import com.fzc.rhinooffice.common.utils.CommonUtil;
import com.fzc.rhinooffice.common.utils.JsonUtil;
import com.fzc.rhinooffice.common.utils.StringUtil;
import com.fzc.rhinooffice.common.view.CustomProgress;
import com.fzc.rhinooffice.module.BaseActivity;
import com.fzc.rhinooffice.module.CommonAdapter;
import com.fzc.rhinooffice.module.ViewHolder;
import com.fzc.rhinooffice.module.entity.AttachmentRecord;
import com.fzc.rhinooffice.module.entity.Email;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@SuppressLint("NewApi")
@ContentView(R.layout.activity_emial_detail)
public class EmailDetailActivity extends BaseActivity implements
		OnItemClickListener {

	@ViewInject(R.id.iv_back)
	private ImageView iv_back;

	@ViewInject(R.id.tv_title)
	private TextView tv_title;

	@ViewInject(R.id.tv_filter)
	private TextView tv_filter;

	@ViewInject(R.id.tv_email_subject)
	private TextView tv_email_subject; // 邮件标题

	@ViewInject(R.id.tv_from_name)
	private TextView tv_from_name; // 发件人

	@ViewInject(R.id.tv_send_time)
	private TextView tv_send_time; // 发件人

	@ViewInject(R.id.ll_attachment_record)
	private LinearLayout ll_attachment_record; // 附件布局

	@ViewInject(R.id.gv_attachment)
	private GridView gv_attachment; // 附件列表

	@ViewInject(R.id.wv_email_content)
	private WebView wv_email_content; // 邮件内容



	private CustomProgress customProgress;

	private Intent mIntent;

	private Email email;

	private CommonAdapter<AttachmentRecord> commonAdapter;

	private List<AttachmentRecord> attachList;

	private long firstTime = 0;
	private int attachClickId = -1;

	public NotificationCompat.Builder mBuilder;
	/** Notification管理 */
	public NotificationManager mNotificationManager;
	
	private PendingIntent pIntent = null;
	
	private RemoteViews remoteView;
	
	/** 下载线程是否暂停 */
	public boolean isPause = false;

	private int progress;
	
	private Notification nitify;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		customProgress = CustomProgress.init(this,
				getResources().getString(R.string.loading), false, null);

		//tv_filter.setVisibility(View.GONE);
		tv_filter.setText("回复");
		tv_filter.setBackgroundDrawable(null);
		tv_title.setText("邮件详细信息");
		gv_attachment.setOnItemClickListener(this);



		getEmailDetail();
		
	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			customProgress.dismiss();
			switch (msg.what) {
			case 3:
				// 获取邮件详情成功
				JSONObject jsonObject = (JSONObject) msg.obj;
				if (jsonObject != null) {
					try {

						if (!StringUtil.isEmpty(jsonObject.getString("record"))) {
							// String str =
							// "{\"from_id\":\"admin\",\"from_name\":\"管理员\",\"subject\":\"APP邮件测试\",\"content\":\"APP邮件测试\",\"send_time\":\"2015-04-29 17:03:23\",\"attachment_rows\":\"0\",\"attachment_record\":NULL}";

							// email = JsonUtil.analysis_email(str);
							email = JsonUtil.analysis_email(new JsonReader(
									new StringReader(jsonObject
											.optString("record"))));

							initUI();
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				break;

			case -3:
				// 获取邮件详情失败
				String reason = (String) msg.obj;
				StringUtil.showToast(getApplicationContext(), reason);
				finish();
				break;
			case 4:
				// 开始下载
				//total = msg.arg1;
				initNotify(msg.arg2);
				break;
			case 5:
				// 正在下载
				progress = msg.arg1;
				setNotify(progress,msg.arg2);
				
				break;

			case 6:
				// 下载完成
				
				closeProcess(msg.arg2,"下载完成");
				break;

			case 7:
				// 下载失败
				closeProcess(msg.arg2,"下载失败");
				break;
			}
		}

	};

	private void getEmailDetail() {
		mIntent = getIntent();
		customProgress.show();
		if (StringUtil.isEmpty(mIntent.getStringExtra("email_id"))) {
			StringUtil.showToast(this, "系统错误！");
			finish();
		} else {
			int emailId = Integer.parseInt(mIntent.getStringExtra("email_id"));
			RemoteInvoke.email_detail(mHandler, emailId);
		}

	}

	private void initUI() {
		LogUtils.i("-email->>" + email);

//		------邮件详情----responseInfo------->>{"state":"1","reason":"","record":{"from_id":"admin","from_name":"管理员","subject":"邮件标题","content":"APP测试内部邮件","send_time":"2015-06-02 11:06:09","attachment_rows":"0","attachment_record":""}}
		if (StringUtil.isEmpty(email.subject)) {
			tv_email_subject.setText("邮件标题：\u3000\u3000未知标题");
		} else {
			tv_email_subject.setText("邮件标题：\u3000\u3000" + email.subject);
		}

		if (StringUtil.isEmpty(email.from_name)) {
			tv_from_name.setText("发  件  人：\u3000\u3000未知发件人");
		} else {
			tv_from_name.setText("发  件  人：\u3000\u3000" + email.from_name);
		}

		if (StringUtil.isEmpty(email.send_time)) {
			tv_send_time.setText("发件时间：\u3000\u3000未知");
		} else {
			tv_send_time.setText("发件时间：\u3000\u3000" + email.send_time);
		}

		if (StringUtil.isEmpty(email.content)) {
			// tv_email_content.setText("无");
		} else {
			try {
				CommonUtil.loadDataWithTransparency(wv_email_content,
						email.content);
				// wv_email_content.loadData(email.content,
				// "text/html; charset=UTF-8", null);

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		// 附件
		if (email.attach_list != null && email.attach_list.size() != 0) {
			ll_attachment_record.setVisibility(View.VISIBLE);
			initAdapter();
		} else {
			ll_attachment_record.setVisibility(View.GONE);
		}
	}

	private void initAdapter() {
		if (commonAdapter == null) {
			commonAdapter = new CommonAdapter<AttachmentRecord>(this,
					email.attach_list, R.layout.attachment_record_item) {

				@Override
				public void convert(ViewHolder holder, AttachmentRecord item) {

					holder.setText(R.id.attach_name, item.name);
				}
			};
			gv_attachment.setAdapter(commonAdapter);
		} else {
			commonAdapter.notifyDataSetChanged();
		}
	}

	@OnClick({ R.id.iv_back, R.id.tv_title })
	private void goBack(View v) {
		super.back();
	}
	
	@OnClick(R.id.tv_filter)
	private void reply(View v) {
		mIntent = new Intent(this,AddEmailActivity.class);
		mIntent.putExtra("from_id", email.from_id);
		startActivity(mIntent);
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		AttachmentRecord attach = email.attach_list.get(position);
		LogUtils.i(attach.url);
		if (StringUtil.isEmpty(attach.url)) {
			StringUtil.showToast("附件已损坏！");
		} else {

			long secondTime = System.currentTimeMillis();

			if ((secondTime - firstTime) > 2000 || attachClickId != position) {
				StringUtil.showToast("再次点击开始下载附件！");
				firstTime = secondTime;
				attachClickId = position;
			} else {
				
				RemoteInvoke.downloadFile(mHandler, attach.url, attach.name,position);
			}

		}

	}

	/** 初始化通知栏 */
	private void initNotify(int notifyId) {
		mBuilder = new NotificationCompat.Builder(this);
		
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		remoteView = new RemoteViews(getPackageName(), R.layout.view_custom_progress);
		remoteView.setProgressBar(R.id.custom_progressbar, 100, 0, false);
		remoteView.setTextViewText(R.id.tv_custom_progress_status, "开始下载");
		
		remoteView.setTextViewText(R.id.tv_custom_progress_time,StringUtil.getCurrentTimeStr("HH:mm"));
		remoteView.setImageViewResource(R.id.custom_progress_icon, R.drawable.ic_launcher);
		
		mBuilder.setContent(remoteView)
				.setSmallIcon(R.drawable.ic_launcher)
				.setDefaults(Notification.DEFAULT_VIBRATE)
				.setContentIntent(getDefalutIntent(Notification.FLAG_ONGOING_EVENT));
		nitify = mBuilder.build();
		//nitify.flags = Notification.FLAG_AUTO_CANCEL;
		mNotificationManager.notify(notifyId, nitify);
	}

	/**
	 * @获取默认的pendingIntent,为了防止2.3及以下版本报错
	 * @flags属性: 在顶部常驻:Notification.FLAG_ONGOING_EVENT 点击去除：
	 *           Notification.FLAG_AUTO_CANCEL
	 */
	private PendingIntent getDefalutIntent(int flags) {
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 1,
				new Intent(), flags);
		return pendingIntent;
	}

	/** 设置下载进度 */
	private void setNotify(int progress,int notifyId) {
		remoteView.setProgressBar(R.id.custom_progressbar, 100, progress, false); // 这个方法是显示进度条
		mNotificationManager.notify(notifyId, mBuilder.build());
	}

	private void closeProcess(int nitifyId,String status) {
		if (mBuilder == null || mNotificationManager == null) {
			return;
		}
		if("下载完成".equals(status)){
			remoteView.setProgressBar(R.id.custom_progressbar,100, 100, false);
			remoteView.setTextViewText(R.id.tv_custom_progress_status, "下载完成");
		}else if("下载失败".equals(status)){
			remoteView.setProgressBar(R.id.custom_progressbar,0, 0, false);
			remoteView.setTextViewText(R.id.tv_custom_progress_status, "下载失败");
		}
		mNotificationManager.notify(nitifyId, nitify);
		//mNotificationManager.cancel(nitifyId);
	}


}
